package sg.edu.nus.comp.icreate.ivletalk.module;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Log;

import sg.edu.nus.comp.icreate.ivletalk.utils.xml.AbstractXmlParser;

public class ModuleListXmlParser extends AbstractXmlParser {

	private static final String TAG_COURSE_CODE = "CourseCode";
	private static final String TAG_COURSE_NAME = "CourseName";
	private static final String TAG_COURSE_ID = "ID";

	public ModuleListXmlParser(InputStream input) throws XmlPullParserException {
		super(input);
	}

	public ModuleListXmlParser() {
		super();
	}

	@Override
	public Object getResult() {
		int eventType;
		List<Module> moduleList = new ArrayList<Module>();
		try {
			goToTag(TAG_RESULT, XmlPullParser.START_TAG);
			Module module = new Module();
			do {
				eventType = parser.getEventType();
				if (eventType == XmlPullParser.START_TAG && TAG_MODULE.equals(parser.getName())) {
					module = new Module();
				} else if (eventType == XmlPullParser.START_TAG && TAG_COURSE_CODE.equals(parser.getName())) {
					parser.next();
					module.setCode(parser.getText());
				} else if (eventType == XmlPullParser.START_TAG && TAG_COURSE_NAME.equals(parser.getName())) {
					parser.next();
					module.setName(parser.getText());
				} else if (eventType == XmlPullParser.START_TAG && TAG_COURSE_ID.equals(parser.getName())) {
					parser.next();
					module.setId(parser.getText());
				} else if (eventType == XmlPullParser.END_TAG && TAG_MODULE.equals(parser.getName())) {
					moduleList.add(module);
				}
				parser.next();
			} while (parser.getEventType() != XmlPullParser.END_TAG || !TAG_RESULT.equals(parser.getName()));

		} catch (Exception e) {
			Log.e("error", "Error in parse xml", e);
		}
		return moduleList;
	}
}
